<?php
/**
 * Created by PhpStorm.
 * User: Neho
 * Date: 2017/11/12
 * Time: 12:52
 */

namespace app\common\controller;

use think\Controller;
use think\exception\HttpResponseException;
use think\Request;
use think\Response;
use Firebase\JWT\JWT;
use think\Config;

class Base extends Controller
{
    public function _initialize()
    {
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Token');
        header('Access-Control-Allow-Methods: GET, POST, PUT');
        header('Access-Control-Expose-Headers : Token');
        header("Content-type:text/html;charset=utf-8");
        //跨域预请求
        if (strtoupper($_SERVER['REQUEST_METHOD']) == 'OPTIONS') {
            exit;
        }

        if (strpos($this->beforeActionList['Authorization']['except'], strtolower($this->request->action()))) {
            $this->updateToken(false);
        }
    }

    protected $beforeActionList = [
        'Authorization' => ['except' => 'login']
    ];

    protected function customizedResult($success = true, $data, $errorMsg = '', $errorCode = '', array $header = [])
    {
        $result = [
            'success' => $success,
            'data' => $data,
            'error_code' => $errorCode,
            'error_msg' => $errorMsg
        ];
        $type = "json";
        $response = Response::create($result, $type)->header($header);
        throw new HttpResponseException($response);
    }

    protected function Authorization()
    {
        $this->updateToken(true);
    }

    private function noAccess()
    {
        $this->customizedResult(false, null, "2000", "请登陆");
    }

    /*
     * 更新token
     * $requireToken 是否必须token
     **/
    private function updateToken($requireToken)
    {
        $token = Request::instance()->header('Authorization');
        if (isset($token)) {
            $config = Config::get('App');
            $secretKey = $config['secretKey'];
            // 定义载荷
            $currentTime = time();
            $expTime = $currentTime + 30 * 24 * 3600;//30天


            try {
                $decoded = JWT::decode($token, $secretKey, array('HS256'));
                if ($decoded->exp < $currentTime) {
                    if ($requireToken) {
                        $this->noAccess();
                    }
                } else {
                    $payload = array(
                        'iat' => $currentTime, // 有效期
                        'exp' => $expTime,
                        'data' => array(
                            'user_id' => $decoded->data->user_id
                        )
                    );
                    Request::instance()->bind('current_user', $decoded->data);
                    $privateToken = JWT::encode($payload, $secretKey);
                    header('Authorization:' . $privateToken);
                }
            } catch (\Exception    $e) {
                if ($requireToken) {
                    $this->noAccess();
                }
            }
        } else {
            if ($requireToken) {
                $this->noAccess();
            }
        }
    }

    /*
     * 创建token
     * */
    public function createToken($id)
    {
        $config = Config::get('App');
        $secretKey = $config['secretKey'];

        // 定义载荷
        $currentTime = time();
        $expTime = $currentTime + 30 * 24 * 3600;//30天

        try {
            $payload = array(
                'iat' => $currentTime, // 有效期
                'exp' => $expTime,
                'data' => array(
                    'user_id' => $id
                )
            );
            $privateToken = JWT::encode($payload, $secretKey);
            return $privateToken;
        } catch (\Exception    $e) {
            //
        }
    }
}